/*
 * Copyright 2011 The Rusted Roof, LLC.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package org.proteusframework.platformservice.persistence.c14n;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Tacoma Four
 */
final class IntegerArrayC14NHandler extends AbstractC14NHandler
{
    @Override
    public Object fromC14N(byte[] bytes)
    {
        int idx = 0;

        List<Integer> intList = new ArrayList<Integer>();
        DataInputStream intDis = new DataInputStream(new ByteArrayInputStream(bytes));

        try
        {
            while (true)
            {
                intList.add(intDis.readInt());
            }
        } catch (EOFException ignore)
        {

        } catch (IOException e)
        {
            e.printStackTrace();
        }

        int[] intValues = new int[intList.size()];
        for (Integer curValue : intList)
        {
            intValues[idx] = curValue;
            idx++;
        }

        return intValues;
    }

    @Override
    public byte[] toC14N(Object object)
    {
        byte[] intBytes = new byte[0];

        int[] intValues = (int[]) object;
        ByteArrayOutputStream intBaos = new ByteArrayOutputStream();
        DataOutputStream intDos = new DataOutputStream(intBaos);

        String intHeader = PACKED_BLOB_PREFIX + transposeClassName(int[].class.getName()) + PACKED_BLOB_SUFFIX;
        byte[] intHeaderBytes = intHeader.getBytes();
        try
        {
            intDos.write(intHeaderBytes, 0, intHeaderBytes.length);
            for (int curValue : intValues)
            {
                intDos.writeInt(curValue);
            }

            intDos.flush();
            intDos.close();

            intBytes = intBaos.toByteArray();
        } catch (IOException e)
        {
            e.printStackTrace();
        }


        return intBytes;
    }
}
